#include<iostream>
#include<unistd.h>//stdlib.h
#include<cstdlib>
#include<string>
#include<stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include<string.h>

#define N 2
#define NUM 1024

using namespace std;

void Writer(int wfd)
{
    string s = "linux for world";
    pid_t self = getpid();
    int num = 0;

    char buffer[NUM];
    while(true)
    {
        buffer[0] = 0;//字符串清空，提醒当字符串
        snprintf(buffer, sizeof(buffer), "%s-%d-%d",s.c_str(),self,num);
        cout<< buffer<< endl;
        // sleep(1);
        write(wfd, buffer, strlen(buffer));
    }
}

void Reader(int rfd)
{
    char buffer[NUM];

    while(true)
    {
        buffer[0] = 0;
        ssize_t n = read(rfd, buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            cout<<"father get a message["<< getpid() <<"] :"<< buffer <<endl;
        }

    }
}


int main()
{
    int pipefd[N];
    int n = pipe(pipefd);
    if(n < 0) return 1;

    // cout<<"pipefd[0]:"<<pipefd[0]<<" pipefd[1]:"<<pipefd[1]<<endl;

    pid_t id = fork();
    if(id < 0) return 2;
    if(id == 0)
    {
        close(pipefd[0]);
        Writer(pipefd[1]);


        close(pipefd[0]);
        exit(0);
    }

    close(pipefd[1]);
    Reader(pipefd[0]);

    pid_t rid = waitpid(id, nullptr, 0);
    if(rid < 0) return 3;

    close(pipefd[1]);
    return 0;
}
